﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;
using Seagull.BarTender.Print;
using zdmacs;
using static CommonPrintProgram.HttpListererPost;

namespace CommonPrintProgram
{
    public partial class Form1 : Form
    {
        public static int PROCESS_INTERVAL = 5* 1000;
        static HttpListener Listener = null;
        //开始任务标识
        static bool timer4ThreadContinue = false;
        static int testNum = 0;
        Thread timer4Thread;
        private Engine engine = null; // The BarTender Print Engine
        private LabelFormatDocument format = null; // The currently open Format

        private string m_CfgPath = Application.StartupPath;
        public Form1()
        {

            InitializeComponent();
            InitializePrint();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void Initializehttpserver()
        {
            try
            {
                string connect_url= connectBox.Text;
                Listener = new HttpListener();
               // AddAddress(connect_url);
                Listener.Prefixes.Add(connect_url+"/");
                Listener.Start();
                Listen();
               writelog("Listening... 传输入参数格式 paramsStr={name:\" 量见智屏\",type:\"建设工程施工图咨询审查/彩电类\"}");
               writelog("已开启自动打印任务");
               connectBox.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show("启动服务异常："+ex.Message);
                writelog(ex.Message);
                start.Text = "开启自动打印";
                start.BackColor = Color.Red;
            }
        }
        public void AddAddress(string address)
        {
            try
            {
                AddAddress(address, Environment.UserDomainName, Environment.UserName);
            }
            catch (Exception ex) { }
        }

        public void AddAddress(string address, string domain, string user)
        {
            string argsDll = String.Format(@"http delete urlacl url={0}", address);
            string args = string.Format(@"http add urlacl url={0} user={1}\{2}", address, domain, user);
            ProcessStartInfo psi = new ProcessStartInfo("netsh", argsDll);
            psi.Verb = "runas";
            psi.CreateNoWindow = true;
            psi.WindowStyle = ProcessWindowStyle.Hidden;
            psi.UseShellExecute = false;
            Process.Start(psi).WaitForExit();//删除urlacl
            psi = new ProcessStartInfo("netsh", args);
            psi.Verb = "runas";
            psi.CreateNoWindow = true;
            psi.WindowStyle = ProcessWindowStyle.Hidden;
            psi.UseShellExecute = false;
            Process.Start(psi).WaitForExit();//添加urlacl
        }
        private void Auto_Load(object sender, EventArgs e)
        {
           
            //start_Click(sender, e);
        }
        public void closeTimer4Thread()
        {
            timer4ThreadContinue = false;
            try
            {
                if (timer4Thread != null)
                {
                  
                    timer4Thread.Abort();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            timer4Thread = null;
        }

        public void startTimer4Thread()
        {
            try
            {
                timer4ThreadContinue = true;
                timer4Thread = new Thread(new ThreadStart(DoProcess));
                timer4Thread.IsBackground = true;
                timer4Thread.Start();
            }
            catch (Exception ex)
            {
                writelog(ex.Message);
            }

        }
        
        private void start_Click(object sender, EventArgs e)
        {
            if (start.Text == "开启自动打印")
            {
              
                Initializehttpserver();
                start.Text = "关闭自动打印";
                start.BackColor = Color.Blue;

            }
            else
            {
                writelog("已关闭自动打印任务");
                start.Text = "开启自动打印";
                start.BackColor = Color.Red;
                connectBox.Enabled = true;
                Listener.Close();
            }
        }
        private void printButton_Click(object sender, EventArgs e)
        {
            this.btnPrint.Enabled = false;
            this.btnPrint.Text = "请稍等，正打印中...";
            //selectTemllate("brother.btw");
            Hashtable ht= new Hashtable();
           writelog("获取到一条打印数据：[name" + ": " + nameBox.Text+ "]"+""+"[type" + ": " + typeBox.Text+ "][dutyman" + ": " + dutyManBox.Text+ "][dept" + ": " 
                + deptBox.Text+ "][qrcode" + ": " + qrcodeBox.Text+ "]n[code" + ": " + codeBox.Text);
             ht.Add("name", nameBox.Text);
            ht.Add("type", typeBox.Text);
            ht.Add("dutyman", dutyManBox.Text);
            ht.Add("dept", deptBox.Text);
            ht.Add("qrcode", qrcodeBox.Text);
            ht.Add("code", codeBox.Text);
            Bartend_Print(ht);
            this.btnPrint.Text = "打印";
            this.btnPrint.Enabled = true;
           
        }//

        private void selectTemllate(string template)
        {
            // Create and start a new BarTender Print Engine.jm
            try
            {

               
                if (format != null)
                    format.Close(SaveOptions.DoNotSaveChanges);

                //string tmp = Path.GetFullPath(Environment.CurrentDirectory + "\\zcdl.btw");
                //string tmp = Path.GetFullPath(Environment.CurrentDirectory + "\\zcdl_v1.btw");
                string fileLocation = Path.Combine(m_CfgPath, template);
                format = engine.Documents.Open(fileLocation);

            }
            catch (PrintEngineException exception)
            {
                MessageBox.Show("模板错误" + exception);
                // If the engine is unable to start, a PrintEngineException will be thrown.
                // MessageBox.Show(this, exception.Message, "");
                //this.Close(); // Close this app. We cannot run without connection to an engine.
                return;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "");
            }
        }
        private void InitializePrint() 
        {


            engine = new Engine(true);
            // Get the list of printers
            Printers printers = new Printers();
            foreach (Printer printer in printers)
            {
                cboPrinters.Items.Add(printer.PrinterName);
            }

            if (printers.Count > 0)
            {
                // Automatically select the default printer.
                cboPrinters.SelectedItem = printers.Default.PrinterName;
            }
            else {
                MessageBox.Show("获取打印机失败：请检查是否正确安装打印机");
            }
            selectTemllate("brother.btw");
        }
        /*
         *  printType  打印类型  1、 栈板标签  2、控制器标签  3、发货标签
         */
        private void Bartend_Print(Hashtable ht)
        {
            // 打开 打印机 端口.
            try
            {
                // We lock on the engine here so we don't lose our format object
                // if the user were to click on a format that wouldn't load.
                lock (engine)
                {
                    bool success = true;
                    format.PrintSetup.IdenticalCopiesOfLabel = 1;
                    format.PrintSetup.NumberOfSerializedLabels = 1;

                    // If there are no incorrect values in the copies boxes then print.
                    if (success)
                    {
                        Cursor.Current = Cursors.WaitCursor;
                        // Get the printer from the dropdown and assign it to the format.
                        if (cboPrinters.SelectedItem != null)
                            format.PrintSetup.PrinterName = cboPrinters.SelectedItem.ToString();




                        try
                        {

                            if (ht.Count>= 1)
                            {
                                //标签数据
                                // 获取键的集合
                                ICollection key = ht.Keys;
                               
                                foreach (string k in key)
                                {
                                    format.SubStrings.SetSubString(k, ht[k].ToString());
                                }
                               
                              }
                         }
                        catch (Exception ex1) { }
                        //format.SubStrings.SetSubString("customer", Print.customer);
                        Messages messages;
                        int waitForCompletionTimeout = 10000; // 10 seconds
                        Result result = format.Print("", waitForCompletionTimeout, out messages);
                        //writelog(result.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("打印异常：" + ex.Message);
                return;
            }
        }


        private void writelog(string message)
        {
            if (this.datalist.Items.Count > 20)
            {
                this.datalist.Items.RemoveAt(20);
            }
            this.datalist.Items.Insert(0, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "  " + message);
            this.datalist.Items.Insert(1, "");
            //LogHelper.WriteLog(message);

        }

        private void DoProcess()
        {
            try {
                Thread.Sleep(1000);
                while (timer4ThreadContinue)
                {
                    // test code
                    if (testNum > 0)
                    {
                       // Bartend_Print(1);
                        testNum--;
                    }
                    timer4ThreadContinue = false;
                    //获取打印任务
                    string url = Print.ServerUrl + "Open/Print/printtag";
                    HttpPostBean httpPost = new HttpPostBean(url);
                    JObject postedJObject = new JObject();
                    String paramString = postedJObject.ToString(Newtonsoft.Json.Formatting.None, null);
                  
                    httpPost.AddKeyValue("String", paramString);
                    string ret = httpPost.Request();
                    //writelog("获取到一条打印任务" + ret);



                }
            }
            catch (Exception ex)
            {
                writelog("操作异常"+ex.Message);
                closeTimer4Thread();
            }
        }

        private async void Listen()
        {
            try
            {
                while (true)
                {

                    var context = await Listener.GetContextAsync();
                    Console.WriteLine("Client connected");
                    Task.Factory.StartNew(() => ProcessRequest(context));

                }
            }
            catch (Exception e)
            {
            }
            Listener.Close();
        }


        private void ProcessRequest(HttpListenerContext context)
        {
            //Stream stream = context.Request.InputStream;
            //System.IO.StreamReader reader = new System.IO.StreamReader(stream, Encoding.UTF8);
            //string body = reader.ReadToEnd();
            int statusCode = 0;
            String message = "";

            string paramsStr = context.Request.QueryString["paramsStr"];
            writelog(paramsStr);
            writelog("第一次获取数据是");

            paramsStr = DecodeBase64("utf-8", paramsStr);
            writelog(paramsStr);
            writelog("第二次解码成urlcode");
            paramsStr =System.Web.HttpUtility.UrlDecode(paramsStr);
            //paramsStr = Encoding.GetEncoding("utf-8").GetString(context.Request.ContentEncoding.GetBytes(paramsStr));
            writelog(paramsStr);
            writelog("第三次解码");
            // writelog(paramsStr);


            //paramsStr = Encoding.GetEncoding("utf-8").GetString(context.Request.ContentEncoding.GetBytes(paramsStr));
           // writelog(paramsStr);
            int count = 0;
            JObject jo = new JObject();
            jo = JObject.Parse(paramsStr);
            try {
                //selectTemllate("brother.btw");
                Hashtable ht = new Hashtable();
                String str = "获取到一条打印数据：";
                foreach (var item in jo)
                {
                    str += "[" + item.Key + ": " + item.Value + "]";
                    ht.Add(item.Key, item.Value);
                }
                writelog(str);

               Bartend_Print(ht);
                statusCode = 200;

            }
            catch(Exception ex)
            {
                writelog("操作出错："+ex.Message);
                message= ex.Message;
            }
            HttpListenerResponse response = context.Response;//响应
            JObject postedJObject = new JObject();
            postedJObject.Add("statusCode", statusCode);
            postedJObject.Add("message", message);
            String paramString = postedJObject.ToString(Newtonsoft.Json.Formatting.None, null);
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(paramString);
            //对客户端输出相应信息.
            response.ContentLength64 = buffer.Length;
            Stream output = response.OutputStream;
            output.Write(buffer, 0, buffer.Length);
            //关闭输出流，释放相应资源
            output.Close();

        }

        ///解码
        public static string DecodeBase64(string code_type, string code)
        {
            string decode = "";
            byte[] bytes = Convert.FromBase64String(code);
            try
            {
                decode = Encoding.GetEncoding(code_type).GetString(bytes);
            }
            catch
            {
                decode = code;
            }
            return decode;
        }

        private void ProcessRequest2(HttpListenerContext context)
        {
            //Stream stream = context.Request.InputStream;
            //System.IO.StreamReader reader = new System.IO.StreamReader(stream, Encoding.UTF8);
            //string body = reader.ReadToEnd();
            int statusCode = 0;
            String message = "";

           //string paramsStr = context.Request.QueryString["paramsStr"];
            //paramsStr = Encoding.GetEncoding("utf-8").GetString(context.Request.ContentEncoding.GetBytes(paramsStr));
           // writelog(paramsStr);
            //获取Post请求中的参数和值帮助类
            HttpListenerPostParaHelper httppost = new HttpListenerPostParaHelper(context);
            //获取Post过来的参数和数据
            List<HttpListenerPostValue> lst = httppost.GetHttpListenerPostValue();
            int count = 0;
            JObject jo = new JObject();
            try
            {
                //selectTemllate("brother.btw");
                Hashtable ht = new Hashtable();
                String str = "获取到一条打印数据：";
                foreach (var key in lst)
                {
                    string value = Encoding.UTF8.GetString(key.datas).Replace("\r\n", "");
                    if (key.name == "paramsStr")
                    {
                        jo = JObject.Parse(value);
                    }

                }
                foreach (var item in jo)
                {
                    str += "[" + item.Key + ": " + item.Value + "]";
                    ht.Add(item.Key, item.Value);
                }
                writelog(str);

                Bartend_Print(ht);
                statusCode = 200;
            }
            catch (Exception ex)
            {
                writelog("操作出错：" + ex.Message);
                message = ex.Message;
            }
            HttpListenerResponse response = context.Response;//响应
            JObject postedJObject = new JObject();
            postedJObject.Add("statusCode", statusCode);
            postedJObject.Add("message", message);
            String paramString = postedJObject.ToString(Newtonsoft.Json.Formatting.None, null);
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(paramString);
            //对客户端输出相应信息.
            response.ContentLength64 = buffer.Length;
            Stream output = response.OutputStream;
            output.Write(buffer, 0, buffer.Length);
            //关闭输出流，释放相应资源
            output.Close();

        }


    }//class 
}//main
